<script lang="ts" setup>
import * as CatalogApi from '@/api/course/catalog'
import * as ItemApi from '@/api/course/item'
import EditCatalogForm from './form/edit-catalog-form.vue'
import ViewItemsForm from './form/view-items-form.vue'
import { catalogStatusDict } from './common'
import { listToTree } from '@/utils/tree'
const route = useRoute()

const { courseId } = route.query as unknown as { courseId: string }

/** 完整目录列表 */
const catalogList = ref<CatalogApi.CatalogVO[]>([])
/** 目录id-item列表 映射 */
const catalogItemMap = ref<Record<CatalogApi.CatalogVO['id'], ItemApi.CourseItemVO[]>>({ 0: [] })
/** 完整目录树 */
const catalogTree = computed(() =>
  listToTree<CatalogApi.CatalogTree>(catalogList.value, { pid: 'parentId' })
)

/** 初始化目录数据 */
const initData = async () => {
  const [_catalogList, _catalogItemMap] = await Promise.all([
    CatalogApi.getListByCourseId(courseId),
    ItemApi.getListByCourseId(courseId).then((_itemList) =>
      _itemList.reduce(
        (map, item) => {
          map[item.catalogId] = map[item.catalogId] || []
          map[item.catalogId].push(item)
          return map
        },
        { 0: [] }
      )
    )
  ])
  _catalogList.push({
    id: 0,
    parentId: '',
    catalogName: '根目录',
    catalogDesc: '',
    catalogStatus: 1,
    sortNo: 0
  })
  catalogList.value = _catalogList
  catalogItemMap.value = _catalogItemMap
}
initData()

/** 表格项状态格式化  1 启用 2 禁用*/
const statusFormatter = (val: CatalogApi.CatalogStatus) => {
  const status = catalogStatusDict.find((item) => item.value === val)
  return {
    type: status?.type,
    text: status?.label
  }
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, currentCatalogId = '', id?: number) => {
  formRef.value.open(type, catalogTree.value, currentCatalogId, courseId, id)
}

/** 删除操作 */
const handleDelete = async (id: string) => {
  const isSuccess = await CatalogApi.deleteById(id)
  if (isSuccess) {
    initData()
  }
}

/** 挂载内容管理弹窗 */
const viewItemsFormRef = ref()
const openViewItemsForm = (id: string) => {
  viewItemsFormRef.value.open(courseId, id)
}
</script>

<template>
  <!-- <ContentWrap>
    <el-button type="primary" @click="openForm('create')">添加目录</el-button>
  </ContentWrap> -->

  <ContentWrap>
    <el-table :data="catalogTree" style="width: 100%; margin-bottom: 20px" row-key="id" border>
      <el-table-column prop="catalogName" label="标题" sortable />
      <el-table-column prop="catalogDesc" label="描述" sortable />
      <el-table-column prop="sortNo" label="排序" sortable width="80" />
      <el-table-column prop="catalogStatus" label="状态" sortable width="85">
        <template #default="scope">
          <el-tag class="ml-2" :type="statusFormatter(scope.row.catalogStatus).type">{{
            statusFormatter(scope.row.catalogStatus).text
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            v-hasPermi="['train:course:update']"
            @click="openForm('update', '', row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            v-hasPermi="['train:course:update']"
            @click="openForm('create', row.id)"
          >
            添加子目录
          </el-button>
          <el-button
            link
            type="primary"
            v-hasPermi="['train:course:query']"
            @click="openViewItemsForm(row.id)"
          >
            挂载内容
          </el-button>
          <el-popconfirm title="确认删除？" @confirm="handleDelete(row.id)">
            <template #reference>
              <el-button v-hasPermi="['train:course:delete']" link type="danger"> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 目录编辑弹窗 -->
  <EditCatalogForm ref="formRef" @success="initData" />
  <!-- 挂载内容管理弹窗 -->
  <ViewItemsForm ref="viewItemsFormRef" />
</template>
